﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using popLib;
using PhotoMgr.src.common;
using System.Windows.Forms;
using System.Data;

namespace PhotoMgr.src.database
{
    public partial class DBManager
    {
        public static ReturnSet Search_Category(int page, int itemPerPage, Hashtable searchData)
        {
            var entity = new PhotoMgrEntities(GenConnectionString());

            IQueryable<Category> result = entity.Categories.OrderBy(x => x.CategoryName);

            if (searchData.ContainsKey("CategoryName"))
            {
                string CategoryName = searchData["CategoryName"].ToString();
                result = result.Where(x => x.CategoryName.Contains(CategoryName));
            }

            if (searchData.ContainsKey("CategoryAbbriaviate"))
            {
                string CategoryAbbriaviate = searchData["CategoryAbbriaviate"].ToString();
                result = result.Where(x => x.CategoryAbbriaviate.Contains(CategoryAbbriaviate));
            }

            if (searchData.ContainsKey("Status"))
            {
                string Status = searchData["Status"].ToString();
                result = result.Where(x => x.Status == Status);
            }                        

            return ProcessPageData(page, result, itemPerPage);            
        }

        public static void Fill_Category(ComboBox control, bool showSelectAll)
        {
            List<Category> result = Fill_Category();
            if (showSelectAll)
            {
                Category item = new Category();
                item.CategoryID = 0;
                item.CategoryName = "Tất cả";
                result.Insert(0, item);
            }
            control.DataSource = result;
            control.DisplayMember = "CategoryName";
            control.ValueMember = "CategoryID";
        }

        public static List<Category> Fill_Category()
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                return entity.Categories.Where(x => x.Status == "A").ToList();
            }
        }

        public static Category Category_GetIDFromLetter(string letter)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                var rs = entity.Categories.Where(x => x.CategoryAbbriaviate == letter.ToUpper().Trim());
                Category result;
                if (rs.Count() > 0)
                {
                    result = rs.First();                    
                }
                else
                {
                    result = entity.Categories.Where(x => x.CategoryAbbriaviate == "UC").First();
                }
                return result;
            }
        }

        public static String GetCategoryName(int category_id)
        {
            var entity = new PhotoMgrEntities(GenConnectionString());

            return entity.Categories.Where(x => x.CategoryID == category_id).First().CategoryName;
        }

        public static Category Detail_Category(int category_id)
        {
            Category artistR;
            var entity = new PhotoMgrEntities(GenConnectionString());

            IQueryable<Category> result = entity.Categories.Where(x => x.CategoryID == category_id);

            if (result.Count() < 1)
            {
                return null;
            }

            if (result.Count() == 1)
            {
                artistR = result.First();
            }
            else
            {
                MessageBox.Show("Có nhiều thể loại trủng trong cơ sở dữ liệu", "Thông báo");
                artistR = result.First();
            }

            return artistR;
        }

        public static ReturnSet Save_Category(bool isUpdateMode, Category updatedItem, Category originalItem)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                using (var transaction = entity.BeginTransaction())
                {
                    try
                    {
                        //save Bao Cao BHXH first============================================
                        entity.Categories.Attach(updatedItem);

                        if (isUpdateMode)
                        {
                            entity.ApplyOriginalValues("Categories", originalItem);
                        }
                        else
                        {
                            entity.ObjectStateManager.ChangeObjectState(updatedItem, EntityState.Added);
                        }

                        entity.SaveChanges();
                        transaction.Commit();

                        return new ReturnSet(true, updatedItem);
                    }
                    catch (OptimisticConcurrencyException ocex)
                    {
                        entity.Categories.Detach(updatedItem);
                        transaction.Rollback();
                        Global.WriteLog(ocex, "Save_HanhChanh_LuongCanBans.OptimisticConcurrencyException");
                        return new ReturnSet(false, Global.DBErrorType.RecordOutOfDate, ocex.Message);
                    }
                    catch (UpdateException uex)
                    {
                        entity.Categories.Detach(updatedItem);
                        transaction.Rollback();
                        Global.WriteLog(uex, "Save_HanhChanh_LuongCanBans.UpdateException");
                        Global.WriteLog(uex.InnerException, "Save_KeToan_ChiPhiCongNoNoiTru.UpdateException.InnerException");
                        return new ReturnSet(false, Global.DBErrorType.AddExistedRecord, uex.Message);
                    }
                    catch (Exception ex)
                    {
                        entity.Categories.Detach(updatedItem);
                        transaction.Rollback();
                        Global.WriteLog(ex, "Save_HanhChanh_LuongCanBans.Exception");
                        Global.WriteLog(ex.InnerException, "Save_KeToan_ChiPhiCongNoNoiTru.Exception.InnerException");
                        return new ReturnSet(false, Global.DBErrorType.UnknownError, ex.Message);
                    }
                }
            }
        }

        public static ReturnSet CheckExistedCategory(string categorySyn)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                String categorySynX = Global.GetString(categorySyn);

                var rs = entity.Categories.Where(x => x.CategoryAbbriaviate == categorySynX);

                if (rs.Count() > 0)
                {
                    Category item = rs.First();
                    return new ReturnSet(true, item.CategoryName);
                }

                return new ReturnSet(false);
            }
        }
    }
}
